import { getFlawCardBySheetBack, getSheetFlawMapBack, getSheetListBack } from '@/api/lot-detail-page';
import { handleFlawTypeParams } from '@/page/split-roll/script/tool';
import { UNIT_TO_M } from '@/utils/constant';
import { makeAutoObservable, runInAction } from 'mobx';
import { Storage } from '@/utils/storage';
import { merageDotInfo } from '@/page/synthesize-map/script/tool';
import { FlawCard, FlawCardBySheetBackT, Sheet, SheetFlawMap } from '@/typings/global';
import commonStore from './common';
import { onlyGetChildFlaw,  } from '@/utils/tool';
import { XandYAxisT } from '@/page/split-roll/type';
import moment from 'moment';

export const lotStore = makeAutoObservable({
  lotId: '' as string,
  layerId: '',
  lotOptMinMax: {
    xMin: 0,
    xMax: 0,
    yMin: 0,
    yMax: 0,
    qrMin: 0,
    qrMax: 0
  } as XandYAxisT,
  sheet: {
    sheetId: 0, // 当前选中分条--map--上面的编号
    flawSum: 0, // 当前选中分条--map--缺陷总数
    headMd: 0, // 当前选中分条在分卷的红线高度
    currentPage: 1,
    total: 0,
    pageSize: 17,
    sheetInfo: {} as Sheet
  },
  card: {
    spin: false, //缺陷卡片页面加载状态
    station: 'doff', //缺陷卡片列表，默认为前制程
    detailFlawRow: {} as FlawCard, //缺陷展示字段
    // flawAlias: Storage.get('flawAlias') ? Storage.get('flawAlias') : {},
    flawAlias: {},
    detailShowDialog: false,
    flawIdChecked: 0,
    flawCard: [] as Array<FlawCard>, //缺陷类型卡片
    currentPage: 1,
    total: 0,
    pageSize: 9
  },
  lotFlawSeriesData: [] as any, // 卷-缺陷地图
  sheetFlawMapOption: {} as SheetFlawMap, // 片-缺陷地图
  lotHeadInfo: {} as Record<string, Record<string, number | string>>, // 头部信息
  sheetListTable: [] as Sheet[], // 片列表
  flawCardList: [], // 缺陷卡片
  flawTypeStorage: {
    // 分卷详情页存储的缺陷类型
    doff: Storage.get('flawTypeLot') ? Storage.get('flawTypeLot').doff : ([] as Array<string | number>),
    pol: Storage.get('flawTypeLot') ? Storage.get('flawTypeLot').pol : ([] as Array<string | number>),
    piantiehou: Storage.get('flawTypeLot') ? Storage.get('flawTypeLot').piantiehou : ([] as Array<string | number>)
  },
  checkedFlawTypePmp: Storage.get('lotId_checkedFlawType') ? Storage.get('lotId_checkedFlawType').checkedFlawType : ([] as Array<number>), // 前制程选中的子缺陷集合
  // 给缺陷别名赋值
  setCardFlawAlias(flawAlias) {
    this.card.flawAlias = flawAlias;
  },
  // 改变选中的缺陷类型
  changeCheckedFlawType(classIdList: Array<number>) {
    this.checkedFlawTypePmp = classIdList;
  },

  /**
   * 触发请求的4种情况
   * 1 初始化
   * 2 点击切换页数
   * 3 点击切换片
   * 4 点击左侧缺陷地图的某个缺陷
   * @param lotId
   * @param commonStore
   * @param sheetId
   * @param sheetPageNum
   * @param flawPageNum
   */
  async changeSheetListReq(lotId: string, commonStore, sheetId?: number, sheetPageNum?: number, flawPageNum?: number) {
    try {
      // 触发请求--初始化或者切换分页 | 切换片
      if (sheetId && sheetPageNum) {
        this.sheet.sheetId = sheetId;
        this.sheet.currentPage = sheetPageNum;
      }
      // 触发请求--点击缺陷地图缺陷点
      if (sheetId && sheetPageNum && flawPageNum) {
        this.card.currentPage = flawPageNum;
      }
      // 请求片列表
      const SheetListBack = await getSheetListBack({
        lotId: lotId,
        pageSize: this.sheet.pageSize,
        pageNum: this.sheet.currentPage
      });

      let sheetListResult = SheetListBack.data.sheetList;
      runInAction(() => {
        this.setSheetListVal(SheetListBack, sheetId, sheetPageNum);
      });
      // 返回的片列表空空数组
      if (!sheetListResult || !sheetListResult.length) {
        this.setEmptyData(true, true, true);
        return;
      }
      if (this.sheet.sheetId) {
        // 请求这一片的缺陷卡片
        await this.changeFlawCardReq(this.sheet.sheetId, this.lotId);
        // 请求这一片的缺陷地图
        await this.changeSheetFlawMapReq(this.sheet.sheetId, commonStore);
      }
    } catch (error) {
      console.log('getSheetListBackError', error);
    }
  },

  /**
   * 请求某个片的缺陷地图--http
   * @param sheetId
   * @param commonStore
   */
  async changeSheetFlawMapReq(sheetId: number, commonStore) {
    try {
      const newParams = handleFlawTypeParams(lotStore, commonStore, { lotId: this.lotId, sheetId: sheetId, layerId: this.layerId });
      const sheetFlawMapBack = await getSheetFlawMapBack(newParams);
      const { flawList } = sheetFlawMapBack.data;
      runInAction(() => {
        this.sheetFlawMapOption.flaws = merageDotInfo(flawList, commonStore);
      });
    } catch (error) {
      console.log('getSheetFlawMapBack', error);
    }
  },
  /**
   * 请求缺陷卡片--http
   * @param sheetId
   * @param lotId
   */
  async changeFlawCardReq(sheetId: number, lotId: string) {
    this.card.spin = true;
    try {
      let Params = {
        lotId: lotId,
        sheetId: sheetId,
        layerId: this.layerId,
        station: this.card.station,
        pageSize: this.card.pageSize,
        pageNum: this.card.currentPage
      } as FlawCardBySheetBackT;
      const station = this.card.station;
      let stationResult;
      let flawMap;
      switch (station) {
        case 'doff':
          stationResult = 'doffResult';
          flawMap = commonStore.doffResult.flawTypeSymbolMap;
          break;
        case 'pol':
          stationResult = 'polResult';
          flawMap = commonStore.polResult.flawTypeSymbolMap;
          break;
        case 'piantiehou':
          stationResult = 'pianResult';
          flawMap = commonStore.pianResult.flawTypeSymbolMap;
          break;
      }
      if (station == 'doff') {
        Params.flawTypeList = this.checkedFlawTypePmp; // 默认勾选的缺陷类型
        // if (this.flawTypeStorage['doff'].length && this.flawTypeStorage['doff'][0] !== 'all') {
        //   Params.flawTypeList = onlyGetChildFlawDoff(this.flawTypeStorage['doff'], commonStore.doffResult.fatherMap, commonStore.doffResult.stationMap);
        // } else if (this.flawTypeStorage['doff'].length && this.flawTypeStorage['doff'][0] === 'all') {
        //   Params.flawTypeList = [...commonStore.doffResult.flawTypeSymbolMap.keys()];
        // }
      } else {
        if (!(this.flawTypeStorage[station].length == 1 && this.flawTypeStorage[station][0] == 'all')) {
          Params.flawTypeList = onlyGetChildFlaw(this.flawTypeStorage[station], commonStore[stationResult].fatherMap);
        }
      }
      const FlawCardBySheetBack = await getFlawCardBySheetBack(Params);
      runInAction(() => {
        const flawCard = FlawCardBySheetBack.data.flawList;
        this.card.flawCard = flawCard.map(item => {
          item.genTime = moment(item.genTime).format('YYYY-MM-DD HH:mm:ss');
          item.flawType = flawMap.get(item.flawType)?.name;
          return item;
        });
        this.card.total = FlawCardBySheetBack.data.total;
        this.card.spin = false;
      });
    } catch (error) {
      console.log('getFlawCardBySheetBack', error);
    }
  },
  /**
   * 请求片列表的数据之后，进行赋值
   * @param SheetListBack
   * @param sheetId
   * @param sheetPageNum
   */
  setSheetListVal(SheetListBack, sheetId?: number, sheetPageNum?: number) {
    this.sheetListTable = SheetListBack?.data?.sheetList.map(sheet => {
      sheet.postScreenTime = moment(sheet.genTime).format('YYYY-MM-DD HH:mm:ss');
      return sheet;
    });
    this.sheet.total = SheetListBack?.data.total;
    if (sheetId && sheetPageNum) {
      const currentSheet = (SheetListBack.data.sheetList as Sheet[]).filter(item => item.sheetId == sheetId)[0];
      this.sheet.flawSum = currentSheet.flawCount;
      this.sheet.headMd = currentSheet.doffMd ? currentSheet.doffMd / UNIT_TO_M : 0;
      this.sheet.sheetInfo = currentSheet;
    } else {
      //更新初始化sheetmap中的标题,并且默认选中列表的第一项
      this.sheet.sheetId = (SheetListBack.data.sheetList[0] as Sheet)?.sheetId || 0;
      this.sheet.flawSum = (SheetListBack.data.sheetList[0] as Sheet)?.flawCount || 0;
      this.sheet.headMd = (SheetListBack.data.sheetList[0] as Sheet)?.doffMd / UNIT_TO_M || 0;
      this.sheet.sheetInfo = SheetListBack.data?.sheetList[0] || {};
    }
  },
  /**
  * 
    当片列表为空时
    1 给片列表设置初始空数据
    2 给片地图设置初始空数据
    3 给片缺陷卡片设置初始空数据
  * @param sheet 
  * @param card 
  * @param sheet_map 
  */
  setEmptyData(sheet?: boolean, card?: boolean, sheet_map?: boolean) {
    if (sheet) {
      this.sheetListTable = [];
      this.sheet.sheetId = 0;
      this.sheet.currentPage = 1;
      this.sheet.total = 0;
      this.sheet.flawSum = 0;
      this.sheet.headMd = 0;
    }
    if (card) {
      this.card.flawCard = [];
      this.card.total = 0;
      this.card.currentPage = 1;
      this.card.flawIdChecked = 0;
    }
    if (sheet_map) {
      this.sheetFlawMapOption.flaws = [];
    }
  }
});

export default lotStore;
